/*********************************************************************/
function saveLocal(key, value) {
  chrome.storage.local.set({ [key]: value });
}
async function getLocal(key) {
  const result = await chrome.storage.local.get([key]);
  return result[key];
}
/*********************************************************************/
$(() => {
  /** */
  $('#searchResult').on('click', 'a', function (evt) {
    const url = $(evt.target).attr('link');
    chrome.tabs.create({
      url,
      active: true
    });
  });
  /*********************************************************************/
  var searchTab,
    nameVal,
    companyVal,
    idVal,
    jobVal,
    plateVal,
    searchStatus = 'unstart',
    result = [];
  $('#nameVal').on('input', function () {
    nameVal = $(this).val();
    saveLocal('nameVal', nameVal);
  });
  $('#companyVal').on('input', function () {
    companyVal = $(this).val();
    saveLocal('companyVal', companyVal);
  });
  // $('#jobVal').on('input', function () {
  //   jobVal = $(this).val();
  //   saveLocal('jobVal', jobVal);
  // });
  $('#searchBtn').click(async function () {
    if (searchStatus == 'searching') {
      return false;
    }
    if (searchStatus == 'end') {
      chrome.runtime.sendMessage({
        type: 'stopupdate'
      });
      searchStatus = 'unstart';
      $('#searchBtn').html('开始检索');
      $('#nameVal').val('');
      $('#companyVal').val('');
      $('#searchResult').html('');
      saveLocal('nameVal', '');
      saveLocal('companyVal', '');
      saveLocal('idVal', '');
      ['baidu', 'sogou', 'biying'].forEach((plate) => {
        $('#' + plate).prop('checked', true);
      });
      return false;
    }

    companyVal = $('#companyVal').val();
    nameVal = $('#nameVal').val();
    jobVal = $('#jobVal').val();
    plateVal = $('input[name="option"]:checked')
      .map(function () {
        return this.value;
      })
      .get();
    if (!nameVal || !companyVal || !jobVal || plateVal.length == 0) {
      return false;
    }
    $('#searchBtn').html('正在搜索···');
    const idVal = await getLocal('idVal');
    /*******************************************/
    chrome.runtime.sendMessage({
      type: 'searching',
      data: {_id:idVal,company: companyVal, name: nameVal, job: jobVal, plate: plateVal }
    });
  });
  /*********************************************************************/
  function getPlate(from) {
    if (from == 'baidu') {
      return '百度';
    } else if (from == 'sogou') {
      return '搜狗';
    } else if (from == 'biying') {
      return '必应';
    }
  }
  /********************************************************************/
  function setSearching(data) {
    //console.log('popup 响应：', data);
    if (data.type == 'unstart') {
      return false;
    }
    if (data.type == 'process') {
      searchStatus = 'searching';
      $('#searchBtn').html('正在搜索···');
    } else if (data.type == 'over') {
      searchStatus = 'end';
      $('#searchBtn').html('搜索完成，点击重置');
    }
    $('#jobVal').val(data.job);
    $('#nameVal').val(data.name);
    $('#companyVal').val(data.company);
    ['baidu', 'sogou', 'biying'].forEach((plate) => {
      $('#' + plate).prop('checked', data.plate.includes(plate));
    });
    var html = '';
    (data.result || []).forEach((item) => {
      html += `<li><span>${item.name}</span><span>${getPlate(item.from)}</span><p>${item.word}<a link="${item.href}" target="_blank">详情</a></p></li>`;
    });

    $('#searchResult').html(html);
  }
  // setTimeout(() => {
  //   chrome.storage.local.get(['searchData'], function (result) {
  //     console.log('Value for username is ', result);
  //   });
  // }, 2000);
  /*********************************************************************/
  async function searchUpdate() {
    const names = await getLocal('nameVal');
    names && $('#nameVal').val(names);
    const company = await getLocal('companyVal');
    company && $('#companyVal').val(company);
    const searchReset = await getLocal('searchReset');
    console.log('searchReset', searchReset);
    if (searchReset) {
      saveLocal('searchReset', '');
      return false;
    }
    chrome.runtime.sendMessage(
      {
        type: 'searchupdate'
      },
      function (request) {
        setSearching(request.data);
      }
    );
  }

  searchUpdate();
  /**********************************************************************/
  chrome.runtime.onMessage.addListener(function (request, sender, sendResponse) {
    if (request.status == 'resultupdate') {
      setSearching(request.data);
    }
    // if (searchStatus == 'end') {
    //   sendResponse({ action: 'end' });
    //   saveToLocalStorage({ ...request, status: 'end' });
    //   return false;
    // } else {
    //   saveToLocalStorage(request);
    // }
    // if (request.status === 'searching') {
    //   setSearching(request);
    //   sendResponse({ message: '继续搜索' });
    // } else if (request.status === 'end') {
    //   setSearching(request);
    //   sendResponse({ message: '收到数据成功' });
    // }
  });
  /*********************************************************************/
});
